package pl.edu.agh.mobicentsVoIP.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.edu.agh.mobicentsVoIP.core.User;
import pl.edu.agh.mobicentsVoIP.database.HSQLFacade;

public class LogInHttpServlet extends HttpServlet {

	public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";

	private String headWithTitle(String title) {
		return (DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n<body>" +
				"<img alt=\"Mobicents\" src=\"/mobicentsVoIP-0.1/images/mobicentsVoIP_logo.jpg\" align=\"middle\" />"+
				"<h4 align=\"right\">" +
				"<a href=\"/mobicentsVoIP-0.1/register\">Wroc do rejestracji</a><br>  "+
				"<a href=\"/mobicentsVoIP-0.1/index.htm\">Wroc do menu</a><br>  " +
				"<a href=\"/mobicentsVoIP-0.1/user/data\">Zaloguj sie</a><br>" +
				"</h4>" +
				"<hr/>");
	}

	private class RegistrationException extends Exception {
		String message;

		RegistrationException(String message) {
			this.message = message;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String login = request.getParameter("login");
		String passwd = request.getParameter("passwd");
		PrintWriter out = response.getWriter();
		out.println(headWithTitle("Rejestrowanie"));
		try {
			if (username == null || login == null || passwd == null)
				throw new RegistrationException(
						"Nalezy wypelnic wszystkie pola");
			HSQLFacade facade = new HSQLFacade();
			if (facade.getUser(username) != null)
				throw new RegistrationException("Login " + username
						+ " zajety - uzytkownik juz obecny w bazie!");
			if (facade.getUserByUserURI(login) != null)
				throw new RegistrationException("URI " + login
						+ " zajete - uzytkownik juz obecny w bazie!");
			String pwd = "";
			try {
				MessageDigest hash = MessageDigest.getInstance("SHA-256");
				hash.update(passwd.getBytes());
				byte byteData[] = hash.digest();
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < byteData.length; i++) {
					sb.append(Integer
							.toString((byteData[i] & 0xff) + 0x100, 16)
							.substring(1));
				}
				pwd = sb.toString();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			User user = new User(username, pwd, login, false);
			facade.registerUser(user);
			out.println("<h3>Uzytkownik " + username
					+ " zarejestrowany</h3><hr>");
		} catch (RegistrationException e) {
			out.println("<h3>Wystapil blad</h3><hr><h4>" + e.message + "</h4>");
		}
	}
}
